package com.bucket.cloud.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bucket.cloud.system.api.model.*;
import com.bucket.cloud.system.api.vo.SystemUserVO;
import com.bucket.cloud.system.dao.*;
import com.bucket.cloud.system.service.ResourcesService;
import com.bucket.cloud.system.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * 用户管理实现类
 */
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, SystemUser> implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private UserResourcesMapper userResourcesMapper;
    @Resource
    private UserPoliceMapper userPoliceMapper;
    @Resource
    private UserPositionMapper userPositionMapper;
    @Resource
    private ResourcesService resourcesService;

    @Override
    public void insertUser(SystemUserAddModel user) {
        user.setId(UUID.randomUUID().toString().replaceAll("-", ""));
//        user.setPassword(DigestUtils.md5Hex(user.getPassword()));
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        user.setPassword(encoder.encode(user.getPassword()));
        userMapper.insert((SystemUser) user);
        insertRelationship(user, false);
    }

    @Override
    public void updateUser(SystemUserAddModel user) {
        if (StringUtils.isNotBlank(user.getPassword())){
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            user.setPassword(encoder.encode(user.getPassword()));
        }
        userMapper.updateById((SystemUser) user);
        insertRelationship(user, true);
    }

    @Override
    public void deleteUser(String[] id) {
        userMapper.deleteBatchIds(Arrays.asList(id));
        userRoleMapper.delete(new QueryWrapper<SystemUserRole>().in("USER_ID", id));
        userPositionMapper.delete(new QueryWrapper<SystemUserPosition>().in("USER_ID", id));
        userPoliceMapper.delete(new QueryWrapper<SystemUserPolice>().in("USER_ID", id));
        userResourcesMapper.delete(new QueryWrapper<SystemUserResources>().in("USER_ID", id));
    }

    @Override
    public void updatePassword(SystemUser user) {
        if (!"".equals(user.getPassword())) {
            user.setPassword(DigestUtils.md5Hex(user.getPassword()));
            userMapper.updateById(user);
        }
    }

    @Override
    public IPage<SystemUser> findTByPage(UserPage user) {
        IPage<SystemUser> pageObj = new Page(user.getPageNumber(), user.getPageSize());
        return userMapper.queryByParams(pageObj, user);
    }

    @Override
    public List<SystemUser> selectByParams(SystemUser systemUser) {
        return userMapper.queryByParams(systemUser);
    }

    @Override
    public SystemUser getThisUserInfo(SystemUser systemUser) {
        List<SystemUser> users = this.selectByParams(systemUser);
        if (users.size() > 0) {
            SystemUserVO user = (SystemUserVO) users.get(0);
            user.setAllResourcesTree(resourcesService.queryUserResources(systemUser));
            return user;
        }
        return null;
    }


    @Override
    public void enable(String[] id, int state) {
        for (String i : id) {
            SystemUser rs = new SystemUser();
            rs.setId(i);
            rs.setState(state);
            userMapper.updateById(rs);
        }
    }

    public void insertRelationship(SystemUserAddModel user, boolean reset) {
        if (reset) {
            userRoleMapper.delete(new QueryWrapper<SystemUserRole>()
                    .eq("user_id", user.getId()));
            userResourcesMapper.delete(new QueryWrapper<SystemUserResources>()
                    .eq("user_id", user.getId()));
            userPoliceMapper.delete(new QueryWrapper<SystemUserPolice>()
                    .eq("user_id", user.getId()));
            userPositionMapper.delete(new QueryWrapper<SystemUserPosition>()
                    .eq("user_id", user.getId()));
        }
        for (String id : user.getRoleId()) {
            SystemUserRole userRole = new SystemUserRole();
            userRole.setRoleId(id);
            userRole.setUserId(user.getId());
            userRoleMapper.insert(userRole);
        }
        for (String id : user.getResourcesId()) {
            SystemUserResources sur = new SystemUserResources();
            sur.setUserId(user.getId());
            sur.setResourcesId(id);
            userResourcesMapper.insert(sur);
        }
        for (String code : user.getPoliceCode()) {
            SystemUserPolice sup = new SystemUserPolice();
            sup.setPoliceCode(code);
            sup.setUserId(user.getId());
            userPoliceMapper.insert(sup);
        }
        for (String code : user.getPositionCode()) {
            SystemUserPosition sup = new SystemUserPosition();
            sup.setPositionCode(code);
            sup.setUserId(user.getId());
            userPositionMapper.insert(sup);
        }
    }

}
